package com.liunian.algorithmstudy.tree;

public class GetMinimumDifference530 extends TreeNode {

	/**
	 给你一个二叉搜索树的根节点 root ，返回 树中任意两不同节点值之间的最小差值 。
	 差值是一个正数，其数值等于两值之差的绝对值。
	 [1564,1434,3048,1,null,null,3184]
	 */
	int diff = 10000;
	int maxValue = -10000;
	public int getMinimumDifference(TreeNode root) {
		travelsal(root);
		return diff;
	}

	private void travelsal(TreeNode root) {
		if (root == null) {
			return;
		}
		travelsal(root.left);
		diff = Math.min(diff, Math.abs(root.val - maxValue));
		if (root.val > maxValue) {
			maxValue = root.val;
		}
		travelsal(root.right);
	}

	// ‼️方法二
	TreeNode preNode = null;
	int minDiff = Integer.MAX_VALUE;
	public int getMinimumDifference1(TreeNode root) {
		if (root == null) {
			return minDiff;
		}
		getMinimumDifference1(root.left);
		if (preNode != null) {
			minDiff = Math.min(minDiff, root.val - preNode.val);
		}
		preNode = root;
		getMinimumDifference1(root.right);
		return minDiff;
	}

}
